<template>
    <div class="login w-full h-[100vh] bg-login-bg bg-fixed bg-cover flex items-center justify-center">
        <div class="mask w-[40%] bg-[rgba(255,255,255,.5)] rounded-custom truncate">
            <div class="title h-[3.75rem] text-center flex items-center justify-center text-[1.5625rem] text-primary">
                你我正少年 心底事无人知 唯彼此心照不宣 共此念
            </div>
            <div class="login w-full sm:w-[80%] md:w-[60%] lg:w-[50%] mx-auto">
                <n-form ref="formRef" class="" :model="userLoginForm" :rules="rules" label-placement="left"
                    label-width="auto">
                    <n-form-item path="username">
                        <n-input v-model:value="userLoginForm.username" size="large" round placeholder="账号或邮箱">
                            <template #prefix>
                                <img :src="user" alt="SVG Image" width="" height="" />
                            </template>
                            <template #suffix>
                                <n-icon :component="FlashOutline" />
                            </template>
                        </n-input>
                    </n-form-item>
                    <n-form-item path="password" label="">
                        <n-input v-model:value="userLoginForm.password" size="large" round type="password"
                            show-password-on="click" placeholder="密码" :maxlength="16" show-count>
                            <template #prefix> <img :src="pwd" alt="SVG Image" width="" height="" /> </template>
                        </n-input>
                    </n-form-item>
                </n-form>
            </div>
            <div class="w-[50%] flex justify-centertext-gray-600 justify-evenly mx-[auto]">
                <div class="flex items-center">
                    <n-checkbox v-model:checked="checked" @update:checked="remenber">记住密码</n-checkbox>
                </div>
                <div class="flex items-center text-blue-500 hover:text-blue-600 cursor-pointer transition-colors duration-200 text-sm hover:underline">
                    <span class="forget-password" @click="forgetpas">忘记密码？</span>
               
        <span class="text-gray-400">|</span>
        <span class="text-emerald-500 hover:text-emerald-600 cursor-pointer transition-colors duration-200 text-sm hover:underline"
              @click="guestLogin">
            游客访问
        </span>

                </div>
                
            </div>
            <div class="btn w-[35%] flex flex-col items-center justify-center mx-[auto] mt-[0.625rem] mb-[0.625rem]">
                <n-button type="info" @click="sub">夢の世界へようこそ[登录]</n-button>
                <n-button type="info" class="mt-[0.125rem]" @click="reg">夢の鍵[注册]</n-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { FlashOutline } from '@vicons/ionicons5'
import { type FormItemRule, type FormRules, type FormInst } from 'naive-ui'
import { useMessage } from 'naive-ui'
import user from '@/assets/icon/user.svg'
import pwd from '@/assets/icon/pwd.svg'
import { getLocal } from '@/utils/token'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/user'
const path = localStorage.getItem('path')
const query = localStorage.getItem('query')
const authStore = useAuthStore()
const router = useRouter()
const message = useMessage()

onMounted(() => {
    if (getLocal('news')) {
        Object.assign(userLoginForm, JSON.parse(getLocal('news') as any))
        checked.value = true
    }
})

// 账号密码
const userLoginForm = reactive({
    username: '',
    password: '',
})
const formRef = ref<FormInst | null>(null)
const checked = ref(false)
// 用户名验证
const valiUser = (
    rule: FormItemRule,
    value: string,
    callBack: any,
    source: Object,
    options: any,
) => {
    if (!value) {
        return new Error('账户不能为空')
    }
    return callBack()
}
// 密码验证
const valiPwd = (
    rule: FormItemRule,
    value: string,
    callBack: any,

) => {
    if (!value) {
        return new Error('密码不能为空')
    }
    return callBack()
}
// 表单验证
const rules: FormRules = {
    username: [
        {
            required: true,
            validator: valiUser,
            trigger: ['blur'],
        },
    ],
    password: [
        {
            required: true,
            validator: valiPwd,
            trigger: ['blur'],
        },
    ],
}
const guestLogin = () => {
    // 游客登录逻辑
    router.push({ path: '/' })
}
// 提交登录
const sub = () => {
    if (formRef.value) {
        formRef.value.validate(async (vali: any) => {
            if (!vali) {
                let res:any = await authStore.login({
                    username: userLoginForm.username,
                    password: userLoginForm.password
                });
                if (res.states) {
                    // 登录成功
                    message.success(res.message)
                    if (path) {
                        // 跳转到登录前的页面
                        router.push({ path: path,query: JSON.parse(query as string) })
                    } else {
                        // 跳转到首页
                        router.push({ path: '/' })
                    }
                    localStorage.removeItem('path')
                } else {
                    // 登录失败
                    message.error("登录失败，请检查账号或密码")
                }
                
            }
        })
    }
}
// 注册
const reg = () => {
    router.push({ path: '/register' })
}
// 记住密码
const remenber = (data: any) => {
    checked.value = data
    if (checked.value) {
        localStorage.setItem('news', JSON.stringify(userLoginForm))
    } else {
        localStorage.removeItem('news')
    }
}
// 忘记密码
const forgetpas = async () => {
    // 忘记密码逻辑
    router.push({ path: '/forget' })
}
</script>

<style lang="scss" scoped></style>
